import React, { useState, useEffect, useRef, useCallback } from "react";
import styles from "./index.module.less";
import {
  NavBar,
  Avatar,
  Space,
  Toast,
  Dialog,
  PullToRefresh,
} from "antd-mobile";
import {
  SendOutlined,
  OpenAIOutlined,
} from "@ant-design/icons";
import {
  AddOutline,
  UpOutline,
  RightOutline,
  DeleteOutline,
  RedoOutline,
  EditSOutline,
  ClockCircleOutline,
} from "antd-mobile-icons";
import { useSearchParams } from "react-router-dom";
import ModelSelector from "@/components/ModelSelector";
import HeaderNav from "@/components/header-nav";
const {
  getChatDetail,
  postChatMessage,
  deleteChatMessage,
  saveChatMessage,
  editChatMessage,
  batchDeleteChatMessage,
  getChatPostMessageUrl
} = $globalServicer("chat");
import { Bubble, Sender } from "@ant-design/x";
import dayjs from "dayjs";
import EditModal from "@/components/editModal";

// 1. 首先创建一个新的 ChatInput 组件
const ChatInput = React.memo(({ 
  onSend, 
  loading, 
  currentModelId,
  onModelChange,
  modelVisible,
  setModelVisible,
  chatId
}) => {
  const [value, setValue] = useState("");
  
  const handleSubmit = useCallback(async (msg) => {
    if (!msg.trim()) return;
    setValue("");
    await onSend(msg);
  }, [onSend]);

  const senderHeaderPrefix = useCallback(() => (
    <div className={styles.senderHeaderPrefix}>
      <OpenAIOutlined onClick={() => setModelVisible(true)} />
    </div>
  ), [setModelVisible]);

  return (
    <div className={styles.button_wrap}>
      {senderHeaderPrefix()}
      <Sender
        value={value}
        onChange={setValue}
        loading={loading}
        onSubmit={handleSubmit}
        placeholder="发消息，AI生成回复"
        onCancel={() => {
          setLoading(false);
        }}
        actions={(_, info) => {
          const { SendButton, LoadingButton } = info.components;
          if (loading) {
            return <LoadingButton />;
          }
          return (
            <SendButton 
              color="primary" 
              shape="default"
              icon={<SendOutlined />}
            />
          );
        }}
      />
    </div>
  );
});

const Detail = () => {
  const customNavigate = $globalNavigate();
  const [params] = useSearchParams();
  const sendId = params.get("chatId");
  const [chatDetail, setChatDetail] = useState({});
  const listRef = useRef(null);
  const [last_id, setLast_id] = useState(0);
  // chat message
  const [value, setValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [chatMessages, setChatMessages] = useState([]);
  const [displayedMessages, setDisplayedMessages] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;
  const [hasMore, setHasMore] = useState(false);
  const [isShowMore, setIsShowMore] = useState(false);
  const [currlentRoles, setCurrentRoles] = useState([
    {
      cover: "",
      name: "",
    },
  ]);
  const [chatPresets, setChatPresets] = useState({
    after: [],
    before: [],
    replace_fields: [],
    chat_num: 0,
  });
  const [editVisible, setEditVisible] = useState(false);
  const [editContent, setEditContent] = useState({
    id: 0,
    message: "",
    send_name: "",
    send_time: "",
    send_cover: "",
  });
  const [chatPersonas, setChatPersonas] = useState({});
  const [modelVisible, setModelVisible] = useState(false);
  const [currentModelId, setCurrentModelId] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isSendingMessage, setIsSendingMessage] = useState(false);

  // 1. 首先定义 scrollToBottom 函数（保持原有实现不变）
  const scrollToBottom = (behavior = 'auto') => {
    if (listRef.current && listRef.current.nativeElement) {
      const listElement = listRef.current.nativeElement;
      console.log('===> listElement (native)', listElement);

      // 获取所有消息元素
      const messageElements = Array.from(listElement.querySelectorAll('.ant-bubble[data-message-id]'));
      console.log('===> 所有消息元素:', messageElements.map(el => el.getAttribute('data-message-id')));

      if (messageElements.length > 0) {
        const lastMessageElement = messageElements[messageElements.length - 1];
        const lastMessageId = lastMessageElement.getAttribute('data-message-id');
        console.log('===> 准备滚动到最后一条消息:', {
          id: lastMessageId,
          element: lastMessageElement
        });

        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
             // 使用 'auto' 避免与可能的平滑滚动冲突，'end' 表示对齐元素底部
             lastMessageElement.scrollIntoView({ behavior, block: 'end' });
            //  lastMessageElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
            console.log('===> 滚动执行完成，最后消息ID:', lastMessageId);
          });
        });
      } else {
        console.warn('未找到最后一个消息元素 (.ant-bubble:last-child)');
        // 可以保留之前的 closest + rAF 代码作为备用方案，但我们已知它效果不佳
        // const scrollContainer = listElement.closest('.adm-pull-to-refresh-content');
        // if (scrollContainer) scrollContainer.scrollTop = scrollContainer.scrollHeight;
      }
    }
  };

  // 2. 然后是其他函数的定义
  const saveMessage = useCallback(async (messageData) => {
    try {
      const saveRes = await saveChatMessage({
        chat_id: sendId,
        records: [messageData],
      });
      return saveRes.ids[0];
    } catch (error) {
      console.error("保存消息失败:", error);
      throw error;
    }
  }, [sendId]);

  const isValidRegex = useCallback((pattern) => {
    try {
      new RegExp(pattern);
      return true;
    } catch (e) {
      console.error("Invalid regex pattern:", pattern, e);
      return false;
    }
  }, []);

  // 2. 定义 checkCanSendMessage
  const checkCanSendMessage = useCallback(() => {
    if (currentModelId === 0) {
      Toast.show({
        content: '请先选择一个模型',
      });
      setModelVisible(true);
      return false;
    }
    return true;
  }, [currentModelId, setModelVisible]);

  // 3. 定义 sendMessage 函数
  const sendMessage = useCallback(async (content) => {
    try {
      // 1. 准备用户消息
      const userMessage = {
        type: 0,
        send_name: chatPersonas.name,
        send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        message: content,
        loading: false,
        cover: chatPersonas.cover,
      };

      // 2. 保存用户消息并获取ID
      const userMessageData = {
        type: 0,
        message: content,
        send_name: userMessage.send_name,
        send_time: userMessage.send_time,
        send_cover: userMessage.cover,
      };
      const userMessageId = await saveMessage(userMessageData);

      // 3. 更新消息列表
      const updatedFullMessages = [...chatMessages, { ...userMessage, id: userMessageId }];
      const updatedDisplayedMessages = [...displayedMessages, { ...userMessage, id: userMessageId }];
      setChatMessages(updatedFullMessages);
      setDisplayedMessages(updatedDisplayedMessages);

      // 4. 添加AI思考中的临时消息
      const pendingMessage = {
        type: 1,
        message: "正在思考中...",
        loading: true,
        send_name: currlentRoles.name,
        cover: currlentRoles.cover,
        send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };
      setChatMessages([...updatedFullMessages, pendingMessage]);
      setDisplayedMessages([...updatedDisplayedMessages, pendingMessage]);

      // 4.1 在显示用户消息和 Pending 后立即滚动到底部
      setTimeout(() => scrollToBottom('smooth'), 0);

      // 5. 获取AI响应
      const messageData = buildMessageData(updatedFullMessages, chatPresets, content);
      const response = await postChatMessage(messageData);
      if (!response?.choices?.[0]?.message?.content) {
        throw new Error("操作异常，疑似网络问题");
      }

      let aiMessage = response.choices[0].message.content;
      let total_tokens = response.usage.total_tokens;

      // 6. 处理AI响应消息
      const replaceFields = chatPresets.replace_fields;
      if (replaceFields.length) {
        replaceFields.forEach((item) => {
          if (item.match_type === "exact") {
            aiMessage = aiMessage.replaceAll(item.search, item?.replace || "");
          }
          if (item.match_type === "regex" && item.search && isValidRegex(item.search)) {
            aiMessage = aiMessage.replaceAll(
              new RegExp(item.search, "g"),
              item?.replace || ""
            );
          }
        });
      }

      // 7. 保存AI响应
      const aiMessageData = {
        type: 1,
        message: aiMessage,
        send_name: pendingMessage.send_name,
        send_time: pendingMessage.send_time,
        send_cover: pendingMessage.cover,
        total_tokens
      };
      const aiMessageId = await saveMessage(aiMessageData);

      // 8. 更新最终消息列表
      const finalAiMessage = {
        ...pendingMessage,
        id: aiMessageId,
        message: aiMessage,
        loading: false,
      };
      
      setChatMessages(prev => {
        const newMessages = [...prev];
        newMessages[newMessages.length - 1] = finalAiMessage;
        return newMessages;
      });
      
      setDisplayedMessages(prev => {
        const newMessages = [...prev];
        newMessages[newMessages.length - 1] = finalAiMessage;
        return newMessages;
      });
      
      setLast_id(aiMessageId);

      // 8.1 在AI回复完成后再次滚动到底部
      setTimeout(() => scrollToBottom('smooth'), 0);

    } catch (error) {
      console.error("发送消息失败:", error);
      // Toast.show({
      //   content: error.message || "发送消息失败，请重试",
      //   type: "error",
      // });
      // 移除思考中的消息
      setChatMessages(prev => prev.filter(msg => !msg.loading));
      setDisplayedMessages(prev => prev.filter(msg => !msg.loading));
    }
  }, [chatMessages, displayedMessages, chatPresets, currlentRoles, chatPersonas, saveMessage, isValidRegex, scrollToBottom]);

  // 4. 最后定义 handleSendMessage
  const handleSendMessage = useCallback(async (content) => {
    try {
      setIsSendingMessage(true);
      if (!checkCanSendMessage()) {
        return;
      }
      await sendMessage(content);
    } finally {
      setIsSendingMessage(false);
    }
  }, [checkCanSendMessage, sendMessage]);

  const handleModelChange = useCallback((modelId) => {
    setCurrentModelId(modelId);
    getChatDetail(sendId).then((res) => {
      setChatPresets(res.presets);
      setChatDetail(res.detail);
    });
  }, [sendId]);

  useEffect(() => {
    if (loading) {
      const timer = setTimeout(() => {
        setLoading(false);
      }, 3000);

      return () => {
        clearTimeout(timer);
      };
    }
  }, [loading]);

  // 角色配置
  // 1. 当前角色 chatPersonas.cover
  // 2. AI角色 currlentRoles.cover
  const roles = {
    assistant: {
      placement: "start",
      // avatar: { icon: <Avatar src={chatPersonas.cover} /> },
      avatar: { icon: <Avatar src={currlentRoles.cover} /> },
      // typing: { step: 5, interval: 20 },
      style: {
        maxWidth: 600,
        marginInlineEnd: 44,
      },
    },
    user: {
      placement: "start",
      // avatar: { icon: <Avatar src={currlentRoles.cover} /> },
      avatar: { icon: <Avatar src={chatPersonas.cover} /> },
      // typing: { step: 5, interval: 20 },
      style: {
        maxWidth: 600,
        marginInlineEnd: 44,
      },
    },
  };
  const buildMessageData = (chatMessages, presets, currentMessage) => {
    return {
      messages: [
        ...presets?.before,
        ...chatMessages.slice(-presets.chat_num).map((msg) => ({
          role: msg.type === 0 ? "user" : "assistant",
          content: msg.message,
        })),
        {
          role: "user",
          content: currentMessage,
        },
        ...presets?.after,
      ],
      stream: false,
      chat_id: chatDetail.id,
    };
  };
  const editMessage = useCallback(async (message) => {
    if (!message) return;

    setEditVisible(true);
    setEditContent({
      id: message.id,
      message: message.message,
      send_name: message.send_name,
      send_time: message.send_time,
      send_cover: message.cover,
    });
  }, []);
  const deleteMessage = useCallback(
    async (id, type) => {
      console.log("🚀 ~ deleteChatMessage ~ id:", {
        id: [id],
      });
      // 1 删除单条消息 2 批量删除消息
      const content =
        type === 1 ? "确定要删除此条消息吗？" : "是否回朔到当前剧情重新开始?";
      Dialog.confirm({
        content,
        onConfirm: () => {
          if (type === 1) {
            deleteChatMessage({
              id: id,
            }).then((res) => {
              console.log("🚀 ~ deleteChatMessage ~ res:", res);
              Toast.show({
                content: "删除成功",
                type: "success",
              });
              fetchAndSetInitialMessages(sendId);
            });
          } else {
            batchDeleteChatMessage({
              id: id,
            }).then((res) => {
              console.log("🚀 ~ deleteChatMessage ~ res:", res);
              Toast.show({
                content: "回溯剧情成功",
                type: "success",
              });
              fetchAndSetInitialMessages(sendId);
            });
          }
        },
      });
    },
    [sendId]
  );
  const renderSend = (
    props = {
      ignoreLoading: false,
      placeholder: "发消息，AI生成回复",
      btnProps: {
        color: "primary",
        shape: "default",
      },
    }
  ) => {
    const { ignoreLoading, placeholder, ...btnProps } = props;

    return (
      <Sender
        value={value}
        onChange={setValue}
        loading={loading}
        onSubmit={async (msg) => {
          if (!msg.trim()) return;
          // 检查是否可以发送消息
          if (!checkCanSendMessage()) {
            return;
          }
          setLoading(true);
          setValue("");
          await sendMessage(msg);
          setLoading(false);
        }}
        placeholder={placeholder}
        onCancel={() => {
          setLoading(false);
        }}
        actions={(_, info) => {
          const { SendButton, LoadingButton } = info.components;
          if (!ignoreLoading && loading) {
            return (
              // <Tooltip title="Click to cancel">
              <LoadingButton />
              // </Tooltip>
            );
          }

          let node = <SendButton {...btnProps} />;

          if (!ignoreLoading) {
            node = <>{node}</>;
          }
          return node;
        }}
      />
    );
  };
  const fetchAndSetInitialMessages = useCallback((chatId) => {
    getChatDetail(chatId).then((res) => {
      console.log("🚀 ~ fetchAndSetInitialMessages ~ res:", res);
      const allMessages = res.chats || [];
      setChatMessages(allMessages);

      // 设置初始显示的最后 pageSize 条消息
      const initialDisplayed = allMessages.slice(-pageSize);
      setDisplayedMessages(initialDisplayed);

      // 设置分页状态
      setCurrentPage(1);
      setHasMore(allMessages.length > pageSize);

      if (allMessages.length) {
        setLast_id(allMessages[allMessages.length - 1].id);
      } else {
        setLast_id(0);
      }
      setCurrentRoles(res.roles);
      setChatPresets(res.presets);
      setChatPersonas(res.personas);
      setChatDetail(res.detail);
      // 设置当前选中的模型ID
      if (res.detail?.mould_id) {
        setCurrentModelId(res.detail.mould_id);
      }
      
      // 使用 setTimeout 确保 DOM 完全更新后再滚动
      setTimeout(() => {
        console.log('===> 初始化完成，准备滚动到底部');
        scrollToBottom('auto');
      }, 300); // 给予足够的时间让 DOM 更新
    });
  }, [pageSize]);
  const getSendMessageUrl = async () => {
    const res = await getChatPostMessageUrl();
    console.log("🚀 ~ getPostMessageUrl ~ res:", res)
    return res.url
  }
  useEffect(() => {
    if (sendId) {
      fetchAndSetInitialMessages(sendId);
    }
  }, [sendId, fetchAndSetInitialMessages]);
  const backWorldBookDetail = () => {
    customNavigate(`/chatlist?tabType=conversations`);
  };
  const handleEditConfirm = async (updatedContent) => {
    if(!checkCanSendMessage()){
      return
    }
    try {
      // 保存编辑后的消息
      const saveMessage = {
        id: updatedContent.id,
        message: updatedContent.message,
      };
      // 更新本地消息列表
      setChatMessages((prevFull) =>
        prevFull.map((msg) =>
          msg.id === updatedContent.id
            ? { ...msg, message: updatedContent.message }
            : msg
        )
      );
      setDisplayedMessages((prevDisplayed) =>
        prevDisplayed.map((msg) =>
          msg.id === updatedContent.id ? { ...msg, message: updatedContent.message } : msg
        )
      );
      await editChatMessage(saveMessage);
      Toast.show({
        content: "修改成功",
        type: "success",
      });
    } catch (error) {
      Toast.show({
        content: "修改失败，请重试",
        type: "error",
      });
    }
  };
  const formateMessage = (message) => {
    // 先清除HTML标签，但保留换行符
    let cleanMessage = message.replace(/<[^>]*>/g, "");
    // 将连续的换行符替换为单个<br/>标签
    cleanMessage = cleanMessage.replace(/\n/g, "<br/>");
    // 匹配引号中的内容并添加样式
    // cleanMessage = cleanMessage.replace(/("|"|")([^""]+)("|"|")/g, '<em style="color: #8B4513;">$1$2$3</em>');
    cleanMessage = cleanMessage.replace(
      /(["“])([^"”]+?)(["”])/g,
      '<em style="color: #db9ea7;">$1$2$3</em>'
    );
    return <div dangerouslySetInnerHTML={{ __html: cleanMessage }} />;
  };
  // 添加重新生成消息的函数
  const regenerateMessage = useCallback(async () => {
    try {
      // 获取所有消息的副本
      const currentFullMessages = [...chatMessages];
      const lastFullMessage = currentFullMessages[currentFullMessages.length - 1];

      // 如果最后一条是AI消息，需要先删除它
      if (lastFullMessage && lastFullMessage.type === 1) {
        // 删除当前AI的回复
        await deleteChatMessage({ id: lastFullMessage.id });
        // 更新完整消息列表，移除最后一条AI消息
        currentFullMessages.pop();
        setChatMessages(currentFullMessages);
        
        // 更新显示的消息列表
        // 只有当最后一条消息在当前显示范围内时才更新displayedMessages
        if (displayedMessages[displayedMessages.length - 1]?.id === lastFullMessage.id) {
          const currentDisplayMessages = [...displayedMessages];
          currentDisplayMessages.pop();
          setDisplayedMessages(currentDisplayMessages);
        }
      }

      // 获取用户的最后一条消息
      const lastUserMessage = currentFullMessages
        .filter((msg) => msg.type === 0)
        .pop();

      if (!lastUserMessage) {
        Toast.show({
          content: "没有找到用户消息，无法重新生成",
          type: "error",
        });
        return;
      }

      // 添加AI思考中的临时消息
      const pendingMessage = {
        type: 1,
        message: "正在思考中...",
        loading: true,
        send_name: currlentRoles.name,
        cover: currlentRoles.cover,
        send_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };

      // 更新完整消息列表
      setChatMessages([...currentFullMessages, pendingMessage]);
      
      // 只有当我们在查看最后一页时，才更新显示的消息
      const isViewingLastPage = displayedMessages.length > 0 && 
        displayedMessages[displayedMessages.length - 1].id === lastFullMessage?.id;
      
      if (isViewingLastPage) {
        setDisplayedMessages(prev => [...prev, pendingMessage]);
      }

      // 重新获取AI响应
      const messageData = {
        messages: [
          ...chatPresets?.before,
          ...currentFullMessages.map((msg) => ({
            role: msg.type === 0 ? "user" : "assistant",
            content: msg.message,
          })),
          ...chatPresets?.after,
        ],
        stream: false,
        chat_id: chatDetail.id,
      };
      
      const response = await postChatMessage(messageData);

      if (!response?.choices?.[0]?.message?.content) {
        Toast.show({
          content: "操作异常，疑似网络问题，重试或联系客服",
          type: "error",
        });
        // 移除思考中的消息
        setChatMessages(currentFullMessages);
        if (isViewingLastPage) {
          setDisplayedMessages(prev => prev.slice(0, -1));
        }
        return;
      }

      let aiMessage = response.choices[0].message.content;

      // 处理替换字段
      const replaceFields = chatPresets.replace_fields;
      if (replaceFields.length) {
        replaceFields.forEach((item) => {
          if (item.match_type === "exact") {
            aiMessage = aiMessage.replaceAll(item.search, item?.replace || "");
          }
          if (
            item.match_type === "regex" &&
            item.search &&
            isValidRegex(item.search)
          ) {
            aiMessage = aiMessage.replaceAll(
              new RegExp(item.search, "g"),
              item?.replace || ""
            );
          }
        });
      }

      // 保存新的AI响应
      const aiMessageData = {
        type: 1,
        message: aiMessage,
        send_name: pendingMessage.send_name,
        send_time: pendingMessage.send_time,
        send_cover: pendingMessage.cover,
      };
      const aiMessageId = await saveMessage(aiMessageData);

      // 更新最终消息
      const finalAiMessage = {
        ...pendingMessage,
        id: aiMessageId,
        message: aiMessage,
        loading: false,
      };

      // 更新完整消息列表
      setChatMessages([...currentFullMessages, finalAiMessage]);
      
      // 只有在查看最后一页时才更新显示的消息
      if (isViewingLastPage) {
        setDisplayedMessages(prev => {
          const newMessages = [...prev];
          // 替换最后一条loading消息
          if (newMessages[newMessages.length - 1]?.loading) {
            newMessages[newMessages.length - 1] = finalAiMessage;
          } else {
            newMessages.push(finalAiMessage);
          }
          return newMessages;
        });
      }
      
      setLast_id(aiMessageId);
      
      // 重新生成后滚动到底部（仅当在最后一页时）
      if (isViewingLastPage) {
        setTimeout(() => scrollToBottom('smooth'), 0);
      }
    } catch (error) {
      console.error("重新生成消息失败:", error);
      Toast.show({
        content: "重新生成失败，请重试",
        type: "error",
      });
    }
  }, [chatMessages, displayedMessages, chatPresets, currlentRoles, sendId, saveMessage, postChatMessage, deleteChatMessage]);
  // 修改 MessageFooter 组件
  const MessageFooter = ({ messageId, messageType, isLastDisplayedMessage }) => {
    // 获取完整的消息对象
    const message = chatMessages.find((msg) => msg.id === messageId);

    const shouldShowRegenerate = useCallback(() => {
      const currentIndex = chatMessages.findIndex(
        (msg) => msg.id === messageId
      );
      // 如果是最后一条消息
      if (isLastDisplayedMessage) return true;
      // 如果是倒数第二条消息，且是用户消息，且最后一条是AI消息
      if (
        currentIndex === chatMessages.length - 2 &&
        messageType === 0 &&
        chatMessages[chatMessages.length - 1]?.type === 1
      ) {
        return true;
      }
      return false;
    }, [messageId, messageType, isLastDisplayedMessage, chatMessages]);

    return (
      <Space>
        <DeleteOutline onClick={() => deleteMessage(messageId, 1)} />
        <EditSOutline onClick={() => editMessage(message)} />
        <ClockCircleOutline onClick={() => deleteMessage(messageId, 2)} />
        {shouldShowRegenerate() && <RedoOutline onClick={regenerateMessage} />}
      </Space>
    );
  };

  // --- 新增：下拉加载更多消息的处理函数 ---
  const loadMoreMessages = async () => {
    if (!hasMore || isLoadingMore) return;
    
    setIsLoadingMore(true);
    
    try {
      // 1. 获取当前第一条可见消息的ID
      const messages = Array.from(listRef.current?.nativeElement?.querySelectorAll('.ant-bubble[data-message-id]') || []);
      const firstMessage = messages[0];
      if (!firstMessage) return;

      const firstMessageId = firstMessage.getAttribute('data-message-id');
      
      // 2. 加载更多消息
      const nextPage = currentPage + 1;
      const startIndex = Math.max(0, chatMessages.length - nextPage * pageSize);
      const endIndex = chatMessages.length - currentPage * pageSize;
      const olderMessages = chatMessages.slice(startIndex, endIndex);

      if (olderMessages.length > 0) {
        // 3. 更新消息列表
        setDisplayedMessages(prev => [...olderMessages, ...prev]);
        setCurrentPage(nextPage);
        setHasMore(startIndex > 0);
        
        // 4. 等待 DOM 更新后，滚动到之前记录的消息位置
        requestAnimationFrame(() => {
          scrollToMessageById(firstMessageId);
        });
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.error('加载更多消息时出错:', error);
      Toast.show({
        content: '加载消息失败，请重试',
        type: 'error'
      });
    } finally {
      setIsLoadingMore(false);
    }
  };
  // --- 结束 ---

  // --- 新增 Effect: 监听 displayedMessages 更新，处理 AI 回复后的滚动 ---
  useEffect(() => {
    const lastMessage = displayedMessages[displayedMessages.length - 1];
    // 只有在发送新消息时才滚动到底部
    if (
      listRef.current && 
      lastMessage && 
      lastMessage.type === 1 && 
      !lastMessage.loading && 
      !isLoadingMore && 
      isSendingMessage
    ) {
      setTimeout(() => scrollToBottom('smooth'), 50);
    }
  }, [displayedMessages, isLoadingMore, isSendingMessage]); // 添加 isSendingMessage 依赖
  // --- 结束 ---

  const scrollToMessageById = (messageId) => {
    // 通过 data-message-id 属性找到目标消息元素
    const targetMessage = document.querySelector(`.ant-bubble[data-message-id="${messageId}"]`);
    
    if (!targetMessage) {
      console.log('未找到目标消息，ID:', messageId);
      return;
    }
    
    // 获取滚动容器
    const scrollContainer = document.querySelector('.adm-pull-to-refresh-content');
    if (!scrollContainer) {
      console.log('未找到滚动容器');
      return;
    }
    
    // 打印目标消息信息
    console.log('目标消息信息:', {
      messageId,
      offsetTop: targetMessage.offsetTop,
      height: targetMessage.offsetHeight,
      containerScrollTop: scrollContainer.scrollTop
    });
    
    // 执行滚动
    targetMessage.scrollIntoView({ behavior: 'auto', block: 'center' });
    
    // 监控滚动效果
    console.log('滚动前位置:', scrollContainer.scrollTop);
    
    // 使用 requestAnimationFrame 确保在下一帧渲染后检查滚动位置
    requestAnimationFrame(() => {
      console.log('滚动后位置:', scrollContainer.scrollTop);
    });
  }

  // 添加视口高度计算
  useEffect(() => {
    const setViewHeight = () => {
      const vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    };

    setViewHeight();
    window.addEventListener('resize', setViewHeight);
    window.addEventListener('orientationchange', setViewHeight);

    // 监听软键盘
    window.visualViewport?.addEventListener('resize', setViewHeight);

    return () => {
      window.removeEventListener('resize', setViewHeight);
      window.removeEventListener('orientationchange', setViewHeight);
      window.visualViewport?.removeEventListener('resize', setViewHeight);
    };
  }, []);

  return (
    <div className={styles.page_container}>
      {/* 顶部导航 - 固定 */}
      <div className={styles.header}>
        <HeaderNav
          onBack={backWorldBookDetail}
          title={currlentRoles.name}
          backArrow={true}
          needConfirm={true}
          right={
            <AddOutline
              onClick={() => customNavigate(`/chatImage?id=${chatDetail.id}`)}
            />
          }
        />
      </div>

      {/* 主要角色区域 - 固定 */}
      {currlentRoles.npcs && currlentRoles.npcs.length > 0 && (
        <div className={styles.role_section}>
          <div className={styles.content_body_top_section_title}>
            <p className={styles.title_left}>主要角色</p>
            <p
              className={styles.title_right}
              onClick={() => setIsShowMore(!isShowMore)}
            >
              {isShowMore ? "收起" : "查看"}{" "}
              <span>{isShowMore ? <UpOutline /> : <RightOutline />}</span>
            </p>
          </div>
          {isShowMore && (
            <div className={styles.content_body_top_section}>
              {currlentRoles?.npcs?.map((item) => (
                <div
                  className={styles.content_body_top_section_select}
                  key={item.id}
                >
                  <img src={item.cover} alt="" />
                  <p className={styles.content_body_top_section_select_name}>
                    {item.name}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 聊天区域 - 可滚动 */}
      <div className={styles.chat_section}>
        <div 
          className={styles.chat_background}
          style={{
            backgroundImage: `url(${chatDetail.image})`,
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover",
            backgroundPosition: "center",
          }}
        />
        <div className={styles.chat_content}>
          <PullToRefresh onRefresh={loadMoreMessages} disabled={!hasMore}>
            <Bubble.List
              ref={listRef}
              roles={roles}
              className={styles.message_list}
              items={displayedMessages.map((message, i) => {
                const isLastDisplayedMessage = i === displayedMessages.length - 1;
                return {
                  header: `${message.send_name}  ${message.send_time}`,
                  key: message.id || i,
                  role: message.type === 1 ? "assistant" : "user",
                  content:
                    message.type === 1
                      ? formateMessage(message.message, message.id || i)
                      : message.message,
                  loading: message.loading,
                  footer: message.id && !message.loading ? (
                    <MessageFooter
                      messageId={message.id}
                      messageType={message.type}
                      isLastDisplayedMessage={isLastDisplayedMessage}
                    />
                  ) : null,
                 'data-message-id': message.id || i
                };
              })}
            />
          </PullToRefresh>
        </div>
      </div>

      {/* 底部发送区域 */}
      <div className={styles.footer}>
        <ChatInput 
          onSend={handleSendMessage}
          loading={isSendingMessage}
          currentModelId={currentModelId}
          onModelChange={handleModelChange}
          modelVisible={modelVisible}
          setModelVisible={setModelVisible}
          chatId={sendId}
        />
      </div>

      {/* 编辑模态框 */}
      {editVisible && (
        <EditModal
          visible={editVisible}
          setVisible={setEditVisible}
          content={editContent}
          onConfirm={handleEditConfirm}
        />
      )}

      {/* 将 ModelSelector 移到这里 */}
      <ModelSelector
        chatId={sendId}
        visible={modelVisible}
        onClose={() => setModelVisible(false)}
        modelId={currentModelId}
        onModelChange={handleModelChange}
      />
    </div>
  );
};

export default Detail;
